package cn.broadsense.common.utils;

import cn.broadsense.common.exception.UtilException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author huangjinshi
 * @description
 * @createDate 2023-09-25 11:12:50
 */
public class VersionUtils {

    // 版本号格式校验的正则表达式
    private static final String VERSION_PATTERN = "^[0-9]+(\\.[0-9]+){0,2}$";

    /**
     * 校验版本号格式是否正确
     *
     * @param version 版本号
     * @return 是否正确
     */
    public static boolean isValidVersion(String version) {
        if (version == null) {
            return false;
        }

        Pattern pattern = Pattern.compile(VERSION_PATTERN);
        Matcher matcher = pattern.matcher(version);

        return matcher.matches();
    }

    /**
     * 比较两个版本号的大小
     *
     * @param version1 版本号1
     * @param version2 版本号2
     * @return 如果version1大于version2，返回1，如果version1等于version2，返回0，如果version1小于version2，返回-1
     */
    public static int compareVersion(String version1, String version2) {
        if (!isValidVersion(version1) || !isValidVersion(version2)) {
            throw new UtilException("版本号格式不正确");
        }

        String[] versionArray1 = version1.split("\\.");
        String[] versionArray2 = version2.split("\\.");

        int index = 0;
        int minLen = Math.min(versionArray1.length, versionArray2.length);

        while (index < minLen) {
            int diff = Integer.parseInt(versionArray1[index]) - Integer.parseInt(versionArray2[index]);
            if (diff != 0) {
                return diff > 0 ? 1 : -1;
            }

            index++;
        }

        return versionArray1.length - versionArray2.length;
    }

}
